import { createRouter, createWebHashHistory } from 'vue-router'
import China from '../views/home/China.vue'
import Province from '../views/home/Province.vue'
import Txmap from '../views/home/Txmap.vue'
import About from '../views/about.vue'
import Login from '../views/login.vue'
import Layout from '../views/layout.vue'
import { getToken } from '../utils/token'

//导入顶部进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const routes = [
  {
    path: '/',
    redirect: '/about',
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      title: '智慧气体管理平台',
    },
    component: Login,
  },
  {
    path: '/layout',
    name: 'layout',
    component: Layout,
    children: [
      {
        path: '/mimicry',
        name: 'mimicry',
        meta: {
          title: '拟态',
        },
        component: () => import('../views/mimicry.vue'),
      },

      {
        path: '/device',
        name: 'device',
        meta: {
          title: '设备',
        },
        component: () => import('../views/device.vue'),
      },
      {
        path: '/device/deviceInfo',
        name: 'deviceInfo',
        meta: {
          title: '设备详情',
        },
        component: () => import('../views/deviceInfo.vue'),
      },
      {
        path: '/warn',
        name: 'warn',
        meta: {
          title: '报警',
        },
        component: () => import('../views/warn.vue'),
      },
      {
        path: '/warn/warnInfo',
        name: 'warnInfo',
        meta: {
          title: '报警详情',
        },
        component: () => import('../views/warnInfo.vue'),
      },
      {
        path: '/about',
        name: 'about',
        component: About,
        children: [
          {
            path: '/about/china',
            name: 'china',
            component: China,
          },
          {
            path: '/about/txmap',
            name: 'txmap',
            component: Txmap,
          },
          {
            path: '/about/province',
            name: 'province',
            component: Province,
          },
        ],
      },
    ],
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

router.beforeEach((to, from, next) => {
  // 1获取路由的元数据信息
  const token = getToken('access_token')
  NProgress.start()
  if (to.path !== '/login') {
    if (token) {
      next()
    } else {
      next({ path: '/login' })
      return
    }
  } else {
    next()
  }
  /* 路由发生变化修改页面title */
  if (to.meta.title) {
    document.title = to.meta.title
  }
})

router.afterEach(() => {
  NProgress.done()
})
export default router
